import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/app.dart';

class AboutScreen extends StatefulWidget {
  @override
  _AboutScreenState createState() => _AboutScreenState();
}

class _AboutScreenState extends State<AboutScreen> {
  String _version = '';
  App _app = App('android');

  @override
  void initState() {
    super.initState();
    _getVersion();
  }

  Future _getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      _version = packageInfo.version;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('关于我们'),
      ),
      body: PublicList(
        children: <Widget>[
          ListTile(
            title: Text('当前版本'),
            trailing: Text(_version),
          ),
          ListTile(
            title: Text('检查更新'),
            trailing: Icon(Icons.chevron_right),
            onTap: () async {
              if (await _app.checkUpgrade(_version)) {
                final res = await showOkCancelAlertDialog(context: context, title: '检查更新', message: '当前最新版本为${_app.version.toString()}, 是否立即更新?', okLabel: '是', cancelLabel: '否');
                if (res == OkCancelResult.ok) {
                  await showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) => UpgradeDialog(url: _app.androidUrl ?? ''),
                  );
                }
              } else {
                await showOkAlertDialog(
                  context: context,
                  title: '检查更新',
                  message: '当前已经是最新版本',
                );
              }
            },
          ),
        ],
      ),
    );
  }
}

class UpgradeDialog extends StatefulWidget {
  UpgradeDialog({Key? key, required this.url}) : super(key: key);

  final String url;

  @override
  _UpgradeDialog createState() => _UpgradeDialog();
}

class _UpgradeDialog extends State<UpgradeDialog> {
  ReceivePort _port = ReceivePort();
  int? _progress;
  String? _taskId;
  DownloadTaskStatus? _status;

  @override
  void initState() {
    super.initState();

    IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      if (data[0] == _taskId) {
        DownloadTaskStatus status = DownloadTaskStatus.values[data[1]];

        if ([DownloadTaskStatus.failed, DownloadTaskStatus.complete, DownloadTaskStatus.canceled].contains(status)) {
          if (status == DownloadTaskStatus.complete) {
            Navigator.of(context).pop();
            FlutterDownloader.open(taskId: _taskId!);
          } else if (status == DownloadTaskStatus.failed) {
            setState(() {
              _status = status;
            });
          }
        } else if (status == DownloadTaskStatus.running) {
          setState(() {
            _progress = data[2];
          });
        }
      }
    });

    FlutterDownloader.registerCallback(downloadCallback);

    startDownload(widget.url);
  }

  startDownload(String url) async {
    Directory? tempDir = await getExternalStorageDirectory();
    if (tempDir != null) {
      File existFile = File(tempDir.path + '/setup.apk');
      if (existFile.existsSync()) {
        existFile.deleteSync();
      }
      _taskId = await FlutterDownloader.enqueue(
        url: url,
        savedDir: tempDir.path,
        fileName: 'setup.apk',
        showNotification: false, // show download progress in status bar (for Android)
        openFileFromNotification: false, // click on notification to open downloaded file (for Android)
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('正在更新'),
      content: _status == DownloadTaskStatus.failed
          ? Text('下载失败')
          : Row(
              children: <Widget>[
                Expanded(
                  child: LinearProgressIndicator(
                    value: _progress == null ? null : _progress! / 100,
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    _progress == null ? '' : '${_progress.toString()}%',
                    textAlign: TextAlign.right,
                  ),
                )
              ],
            ),
      actions: <Widget>[
        TextButton(
            onPressed: () {
              FlutterDownloader.cancel(taskId: _taskId!);
              Navigator.of(context).pop();
            },
            child: Text('取消')),
      ],
    );
  }

  @override
  void dispose() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  static void downloadCallback(String id, int status, int progress) {
    final SendPort? send = IsolateNameServer.lookupPortByName('downloader_send_port');
    if (send != null) {
      send.send([id, status, progress]);
    }
  }
}
